<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use DB;

use App\Http\Requests;
use App\Http\Controllers\Controller;

class CateController extends Controller
{   //
    public function getIndex(Request $request)

    {      
      


        $num=$request->input('num',10); 
      // 检测是否提交查询关键字
        if($request->has('keywords')){
           $cates= DB::table('stype')->select(DB::raw('id,name,pid,path,concat(path,",",id) as npath'))->where('name','like','%'.$request->input('keywords').'%')->orderBy('npath')->paginate($num);
         }else{
            $cates= DB::table('stype')->select(DB::raw('id,name,pid,path,concat(path,",",id) as npath'))->orderBy('npath')->paginate($num);

         }
    
       
         $data=$request->except('page');


          return view('Admin.cate.index',['cates'=>$cates,'data'=>$data]);
    }
   public function getAdd()
    {

         $cates=DB::table('stype')->get();

        return view('Admin.cate.add',['cates'=>$cates]);
    }

    
    public function postInsert(Request $request)
    {
         $data=$request->except('_token');


        //判断是否为顶级分类
        if($data['pid']==0)
        {
            $data['path']='0';

        }else{
            $res=DB::table('stype')->where('id',$data['pid'])->first();

            $data['path']=$res->path.','.$data['pid'];

        }

        $res=DB::table('stype')->insert($data);
        if($res)
        {
            return redirect('/admin/cate/index')->with('success','分类添加成功');
        }else{
            return back()->with('error','分类添加失败');
        }
    }

   
    public function postDel(Request $request)
    {
        // dd($request);
        $id=$request->input('id');
      
        $ss=DB::table('stype')->where('pid',$id)->get();


        
        if($ss){
           return 0;
          }
        $res=DB::table('stype')->where('id',$id)->delete();
        return $res;
        
   }
    

   
    public function getEdit($id)
    {
        $cates=DB::table('stype')->where('id',$id)->first();

        return view('Admin.cate.edit',['cates'=>$cates]);

    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function postUpdate(Request $request)
    {
        $data=$request->except('_token');
        $res=DB::table('stype')->where('id',$data['id'])->update($data);
        if($res){
            return redirect('admin/cate/index')->with('success','用户修改成功');
        }else{
            return back()->with('error','用户修改失败');
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}
